<?php
/**
 * 我写的过滤函数
 *
 * @param $data 输入的信息 利用递归，貌似可以支持多维数组，$k没有过滤
 * @return 返回数组或者字符串
 */
function bob_input($data) {
	if(is_array($data)){
		foreach ($data as $k=>$v){
		    $data[$k]=bob_input($v);
		}
		return $data;
	}else{
	    $data = trim($data);
	    $data = stripslashes($data);
	    $data = htmlspecialchars($data,ENT_QUOTES);
	    return $data;
	}
}

/**
 * 我写的打印变量函数
 * @return 打印变量
 */
 function p() {		
	$num=func_num_args();
	$bianliang=func_get_args();
	for($i=0;$i<$num;$i++){
		echo "<pre>";
		var_dump($bianliang[$i]);
		echo "</pre>";
		echo "<br>";
	}
	exit;
}

/**
 * 生成唯一的订单
 *
 * @return 返回字符串
 */
function uOrderid() {
    $str = date('YmdHis').random(2,'0123456789');
    return $str;
}

/**
 * 检测是否是utf-8格式并转为utf8
 * @param  str  utf8 gbk gb2312
 * @return str
 */
function utf8($str){
	//mb_convert_encoding($str, 'html-entities', 'utf-8');转成html编码
	$str = mb_convert_encoding($str, 'utf-8', mb_detect_encoding($str, ['utf-8','gbk','gb2312']));
	return $str;
}

/**
 * 获取请求ip
 *
 * @return ip地址
 */
function ip() {
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$ip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$ip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	//filter_var($ip,FILTER_VALIDATE_IP) && $ip='';
	return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
}

/**
* 产生随机字符串
*
* @param    int        $length  输出长度
* @param    string     $chars   可选的 ，默认为 0123456789
* @return   string     字符串
*/
function random($length, $chars = '0123456789abcdefghijklmnopqrstuvwxyz') {
	$hash = '';
	$max = strlen($chars) - 1;
	mt_srand();
	for($i = 0; $i < $length; $i++) {
		$hash .= $chars[mt_rand(0, $max)];
	}
	return $hash;
}

/**
 * 验证手机号码的正确性
 *
 * @param    string     $phone   手机号码
 * @return   string     字符串
 */
function verifyPhone($phone) {
    $pattern = "/^1\d{10}$/";
    if(preg_match($pattern, $phone)){
        return true;
    } else {
        return false;
    }
}

/**
 * 发送http请求
 * @param string $url 请求地址
 * @param string $method http方法(GET POST PUT DELETE)
 * @param array $data http请求数据 array
 * @param array $header http请求头
 * @param Int   $type  将data转换成json数据或者key=value数据 0- key=value 1- json
 * @param Int   $synchronous  请求数据类型 0-异步  1-同步
 * @return string|bool
 */
function uCurl($url = '', $data = array(), $method = "POST", $type = 0, $header = array(), $synchronous = 1) {
    //控制请求方法范围
    $httpMethod = array('GET', 'POST', 'PUT', 'DELETE');
    $method = strtoupper($method);
    if (!in_array($method, $httpMethod)) {
        return false;
    }
    //初始化http请求
    $ch = curl_init();
    //格式化发送数据
    if ($data) {
        if ($type == 0) {
            $dataValue = http_build_query($data);
        } elseif ($type == 1) {
            $dataValue = json_encode($data, JSON_UNESCAPED_UNICODE);
        }
//            else{
//                //直接post 数组,一般不考虑数组直接传，因为会引起改变头为multipart/form-data,虽然对于大多数web服务器并没有影响,但是还是有少部分服务器不兼容.
//                $dataValue = $data;
//            }
        if (!empty($dataValue)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $dataValue);
        }
    }
    //同步异步判断
    if ($synchronous) {
        //curl_setopt($ch, CURLOPT_TIMEOUT, 35); // 最大等待时间 包含连接等待时间
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 150); // 在尝试连接时等待的秒数,等待150s没有连接成功就断开
    } else {
        //异步
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);//设置超时时间为5秒,超过1秒则关闭连接
        curl_setopt($ch, CURLOPT_NOSIGNAL, 1);     //注意，毫秒超时一定要设置这个 cURL 7.10时被加入
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, 300); //超时毫秒，cURL 7.16.2中被加入
    }
    //其他选项
    curl_setopt($ch, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($ch, CURLOPT_HEADER, 0);// 设置是否显示返回头信息  1返回 0不返回  调试开启
    curl_setopt($ch, CURLOPT_NOBODY, 0); //不想在输出中包含body部分，设置这个选项为一个非零值
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//获取的信息以文件流的形式返回
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE); //在启用CURLOPT_RETURNTRANSFER的时候，返回原生的（Raw）输出。
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//https 不进行ssl验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    //请求头初始化
    $request_headers = array();
    //$User_Agent = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31';
    //$request_headers[] = 'User-Agent: '. $User_Agent;
    //$request_headers[] = 'Accept: text/html,application/json,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
    if (!empty($header)) {
        foreach ($header as $v) {
            $request_headers[] = $v;
        }
    }
    switch ($method) {
        case "POST":
            $request_headers[] = "X-HTTP-Method-Override: POST";
            curl_setopt($ch, CURLOPT_POST, TRUE);//true to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
            break;
        case "PUT":
            $request_headers[] = "X-HTTP-Method-Override: PUT";
            break;
        case "DELETE":
            $request_headers[] = "X-HTTP-Method-Override: DELETE";
            break;
        case "GET":
            if($data) {
                $url = $url . '?' . $dataValue;
            }
            break;
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);//设置头信息
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式
    //发送请求获取返回响应
    $result['data'] = curl_exec($ch);
    //检查是否有错误发生
    if(curl_errno($ch))
    {
        var_dump(curl_error($ch));//直接在终端或者网页端打印出来
    }
    $result['httpCode'] = curl_getinfo($ch,CURLINFO_HTTP_CODE);
    if (strlen(curl_error($ch)) > 1) {
        $result = false;
    }
    curl_close($ch);
    return $result['data'];
}

//yield读取方式
function readYieldFile($fileName)
{
    $handle = fopen($fileName, 'r');
    while (!feof($handle)) {
        yield fgets($handle);
    }
    fclose($handle);
}

//老式读取方式
function readLocalFile($fileName)
{
    $handle = fopen($fileName, 'r');
    $lines = [];
    while (!feof($handle)) {
        $lines[] = fgets($handle);
    }
    fclose($handle);
    return $lines;
}
//readLocalFile('./all.txt');





?>